<template>
  <view class="flex-col">

    <car-info :value="form"></car-info>

    <view class="page-wrap" :class="canEdit?'bottom115':''">

      <view class="lineBottom10 page-section">
        <uni-section title="GPS续费信息" type="line"/>
      </view>

      <uni-forms ref="form" :value="form" labelWidth="auto" :labelPosition="canEdit?'top':'left'">

        <uni-forms-item name="gpsBrand" label="到期GPS品牌:">
          <uni-easyinput disabled v-if="canEdit" type="text" v-model="form.gpsBrand"/>
          <text v-else class="text-value">{{ form.gpsBrand|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item name="equipmentType" label="到期设备类型:">
          <uni-easyinput disabled v-if="canEdit" type="text" v-model="form.equipmentType"/>
          <text v-else class="text-value">{{ form.equipmentType|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item name="equipmentNo" label="到期设备编号:">
          <uni-easyinput disabled v-if="canEdit" type="text" v-model="form.equipmentNo"/>
          <text v-else class="text-value">{{ form.equipmentNo|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item name="simNo" label="到期SIM卡号:">
          <uni-easyinput disabled v-if="canEdit" type="text" v-model="form.simNo"/>
          <text v-else class="text-value">{{ form.simNo|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item name="installExpireTime" label="安装到期时间:">
          <uni-easyinput disabled v-if="canEdit" type="text" v-model="form.installExpireTime"/>
          <text v-else class="text-value">{{ form.installExpireTime|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item :required="canEdit" name="renewFlag" label="是否需要续费:" :rules="mRule('请选择是否需要续费', 'bind')">
          <zxz-uni-data-select
            @change="renewFlagSel"
            v-model="form.renewFlag"
            dataKey="label"
            dataValue="value"
            v-if="canEdit"
            :localdata="dict.type.gps_is_renewal"></zxz-uni-data-select>
          <dict-tag v-else
                    :options="dict.type.gps_is_renewal"
                    :value="form.renewFlag"/>
        </uni-forms-item>

<!--        <uni-forms-item :required="canEdit && 1==form.renewFlag" name="renewEquipmentType" label="续费设备类型:" :rules="[{-->
<!--                                         required: true,-->
<!--                                         errorMessage: '请选择续费设备类型',-->
<!--                                         validateTrigger: 'bind'-->
<!--                                       }]">-->

        <uni-forms-item :required="canEdit && 1==form.renewFlag" name="renewEquipmentType" label="续费设备类型:" :rules="mRule('请选择续费设备类型', 'bind')">
          <zxz-uni-data-select
            v-model="form.renewEquipmentType"
            dataKey="label"
            dataValue="value"
            v-if="canEdit"
            :localdata="dict.type.gps_device_type"></zxz-uni-data-select>
          <dict-tag v-else
                    :options="dict.type.gps_device_type"
                    :value="form.renewEquipmentType"/>
        </uni-forms-item>

        <uni-forms-item :required="canEdit && 1==form.renewFlag" name="renewEquipmentNo" label="续费设备编号:" :rules="mRule('请选择续费设备编号', 'bind')">
          <zxz-uni-data-select
            @change="val=>form.renewSim = val ? val.simNo:null"
            v-model="form.renewEquipmentNo"
            dataKey="equipmentNo"
            dataValue="equipmentNo"
            v-if="canEdit"
            :localdata="simList"></zxz-uni-data-select>
          <text v-else class="text-value">{{ form.renewEquipmentNo|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item :required="canEdit && 1==form.renewFlag" name="renewSim" label="续费SIM卡号:" :rules="mRule('请选择续费SIM卡号', 'bind')">
          <zxz-uni-data-select
            @change="val=>form.renewEquipmentNo = val ? val.equipmentNo:null"
            v-model="form.renewSim"
            dataKey="simNo"
            dataValue="simNo"
            v-if="canEdit"
            :localdata="simList"></zxz-uni-data-select>
          <text v-else class="text-value">{{ form.renewSim|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item :required="canEdit && 1==form.renewFlag" name="renewYear" label="续费年限:" :rules="mRule('请选择续费年限', 'bind')">
          <zxz-uni-data-select
            @change="renewSel"
            v-model="form.renewYear"
            dataKey="label"
            dataValue="value"
            v-if="canEdit"
            :localdata="renewYearList"></zxz-uni-data-select>
          <text v-else class="text-value">{{ form.renewYear|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item :required="canEdit && 1==form.renewFlag" name="renewPrice" label="续费费用:" :rules="mRule('请输入续费费用')">
          <uni-easyinput v-if="canEdit" type="digit" maxlength="12" v-model="form.renewPrice"
                         placeholder="请输入续费费用"/>
          <text v-else class="text-value">{{ form.renewPrice|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item :required="canEdit && 1==form.renewFlag" name="renewStartTime" label="续费开始时间:" :rules="[{
                                         required: true,
                                         errorMessage: '请选择续费开始时间',
                                         validateTrigger: 'bind'
                                       }]">
          <uni-datetime-picker @change="renewSel" v-if="canEdit" type="datetime" return-type="string" v-model="form.renewStartTime"/>
          <text v-else class="text-value">{{ form.renewStartTime|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item :required="canEdit && 1==form.renewFlag" name="renewEndTime" label="GPS到期时间:" :rules="mRule('请选择GPS到期时间', 'bind')">
          <uni-datetime-picker v-if="canEdit" type="datetime" return-type="string" v-model="form.renewEndTime"/>
          <text v-else class="text-value">{{ form.renewEndTime|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item :required="canEdit && 2==form.renewFlag" name="remark" label="备注:" :rules="mRule('请输入备注')">
          <uni-easyinput v-if="canEdit" type="textarea" maxlength="200" v-model="form.remark"
                         placeholder="请输入备注"/>
          <text v-else class="text-value">{{ form.remark|filterNull }}</text>
        </uni-forms-item>

      </uni-forms>

    </view>

    <exam-flow v-if="!canEdit && form.flowId" :instanceId="form.flowId">
    </exam-flow>
    <view class="button-container" v-if="canEdit">
      <button class="btn-item" @click="submit">提 交</button>
    </view>
  </view>
</template>

<script>

import CarInfo from "@/pages/CarPage/gps/components/carInfo.vue";
import {carWorkOrderInfo, gpsRenew, saveCarGpsRenew, gpsSimInfo} from "@/api/gps/gpsList"
import UniSection from "@/uni_modules/uni-section/components/uni-section/uni-section.vue";

var moment = require('@/utils/moment.js');

export default {
  components: {UniSection, CarInfo},
  dicts: ["gps_is_renewal", "gps_device_type"],
  data() {
    return {
      form: {},
      state: 'write',
      carIds: null,
      renewYearList:[{
        label:"1年",
        value:"1"
      },{
        label:"2年",
        value:"2"
      },{
        label:"3年",
        value:"3"
      },{
        label:"4年",
        value:"4"
      },{
        label:"5年",
        value:"5"
      }],
      simList:[]
    }
  },
  computed: {
    canEdit() {
      return 'write' === this.state;
    }
  },
  onLoad(op) {
    console.log('op', op);
    this.state = op?.state ?? 'write';
    this.carIds = op?.carIds ?? null;

	let title = this.canEdit?'续费工单申请':'续费工单详情';
    if (this.carIds) {
      this.getOldData();
    }
    uni.setNavigationBarTitle({
      title
    })
  },
  methods: {
    getSim() {
      gpsSimInfo({
        carId: this.form.carId
      }).then(res => {
        this.simList = res?.data[0]?.equipmentNo?.split(",")?.map((item, index) => {
          let simList = res?.data[0]?.simNo?.split(",");
          return {
            simNo: simList[index],
            equipmentNo: item,
          }

        }) ?? []
      })
    },
    getOldData() {
      carWorkOrderInfo({carIds: this.carIds, workOrderType: 13}).then(res => {
        let intentData = res.data[0];
        console.log('接到', intentData)

        if (!this.isEmpty(intentData)) {
          if (!this.isEmpty(intentData.businessDataId)) {
            //提报过，请求详情
            this.initData(intentData.businessDataId)
          } else {
            this.form = {...this.form, ...intentData}
            this.getSim()
          }
        }
      })
    },
    renewSel(val){
      if(this.form.renewYear && this.form.renewStartTime){
        let endtime = moment(this.form.renewStartTime, 'YYYY-MM-DD HH:mm:ss').add(Number(this.form.renewYear), 'year').format('YYYY-MM-DD HH:mm:ss')
        this.$set(this.form, 'renewEndTime', endtime)
      }
      this.$forceUpdate()
    },
    // startChange(val){
    //   if(this.form.renewYear && this.form.renewStartTime){
    //     let endtime = moment(this.form.renewStartTime, 'YYYY-MM-DD HH:mm:ss').add(this.form.renewYear, 'year').format('YYYY-MM-DD HH:mm:ss')
    //     this.$set(this.form, 'renewEndTime', endtime)
    //   }
    //   this.$forceUpdate()
    // },
    initData(id) {
      uni.showLoading();
      gpsRenew(id)
        .then((res) => {
          if (res.code == 200) {
            let data = res.data;
            this.form = {...this.form, ...data}
            this.getSim()
          }
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    renewFlagSel(){
      this.$refs.form.clearValidate();
    },
    submit() {
      this.form.contractNo = this.form.contractReportNumber;
      this.form.purchaseNo = this.form.procurementReportNumber;
      this.form.workId = this.form.id;

      let validateList;
      if(1==this.form.renewFlag){
        validateList = ['renewFlag', 'renewEquipmentType', 'renewEquipmentNo', 'renewSim', 'renewYear', 'renewPrice', 'renewStartTime', 'renewEndTime']
      }else if(2==this.form.renewFlag){
        validateList = ['renewFlag', 'remark']
      }else {
        validateList = ['renewFlag']
      }

      this.$refs.form.clearValidate();

      this.$refs.form
        // .validate()
        .validateField(validateList)
        .then(res => {
          uni.showLoading();
          saveCarGpsRenew(this.form).then(response => {
            uni.hideLoading();
            uni.$emit("refreshGps", true);
            this.$modal.msgSuccess("提交成功");
            setTimeout(() => {
              this.$tab.navigateBack();
            }, 1000)
          }).finally(f => {
			setTimeout(() => {
			  uni.hideLoading();
			}, 1000)
          })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
